<template>
  <div>
    <el-card>


      <el-row style="margin-bottom: 10px;">
        <el-col :span="2">
          <el-button type="primary" @click="addButtonClick">添加</el-button>
        </el-col>
        <el-col :span="6">
          <el-input placeholder="搜索用户名" v-model="userQueryInfo.username" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="searchButtonClick"></el-button>
          </el-input>
        </el-col>

      </el-row>
      <el-row style="margin-bottom: 10px;">
        <el-table
          :data="page.list"
          style="width: 100%">
          <el-table-column
            type="selection"
            width="55"
          >

          </el-table-column>
          <el-table-column
            prop="id"
            label="用户ID"
            width="180">
          </el-table-column>
          <el-table-column
            prop="username"
            label="用户名"
            width="180">
          </el-table-column>


          <el-table-column>
            <template slot-scope="scope">
              <el-select
                @change="handleRolesChange(scope.row)"
                style="background-color:lightcyan;color:black;"
                v-model="scope.row.roleIds" multiple placeholder="请选择">
                <el-option

                  v-for="item in allRoles"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">

                  <span> {{item.name}}------{{item.description}}</span>

                </el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column

            label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.state" @change="stateChange(scope.row)" :active-value="1"
                         :inactive-value="0"></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="注册时间">
            <template slot-scope="scope">
              {{formatDateTime(scope.row.createTime)}}
            </template>

          </el-table-column>
          <el-table-column>
            <template slot-scope="scope">
              <el-button plain size="mini" icon="el-icon-edit" type="warning"
                         @click="editButtonClick(scope.row)"></el-button>
              <el-button plain size="mini" icon="el-icon-delete" type="danger"
                         @click="deleteButtonClick(scope.row)"></el-button>
            </template>
          </el-table-column>


        </el-table>
      </el-row>
      <el-row>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNum"
          :page-sizes="[5, 10, 20, 40]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </el-row>

    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="30%"
    >

      用户名:
      <el-input v-model="newUser.username"></el-input>
      密码:
      <el-input v-model="newUser.password"></el-input>
      启用状态:
      <el-switch
        v-model="newUser.state"
        :active-value="1"
        :inactive-value="0"
        active-color="#13ce66"
        inactive-color="#ff4949">
      </el-switch>

      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="confirmAddUserButtonClick">确 定</el-button>
  </span>
    </el-dialog>


    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="30%"
    >

      <el-row>
        <el-col :span="8">
          用户名:
        </el-col>
        <el-col :span="16">
          <el-input size="mini" v-model="currentEditUser.username"></el-input>
        </el-col>
      </el-row>

      <el-row style="margin-top: 10px;">
        <el-col :span="8">
          启&nbsp;&nbsp;&nbsp;用:
        </el-col>
        <el-col :span="16">
          <el-switch v-model="currentEditUser.state" :active-value="1" :inactive-value="0"></el-switch>
        </el-col>
      </el-row>


      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="confirmUpdateUserButtonClick">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
  import {formatDateTime} from "../../../utils/datetime";

  export default {
    name: "index",
    data() {
      return {
        page: {
          pageNum: 0,
          pageSize: 0,
          total: 0,
          totalPages: 0,
          list: []
        },

        userQueryInfo: {
          pageNum: 1,
          pageSize: 5,
          username: ''
        },

        //编辑用户信息的对话框显示开关
        editDialogVisible: false,

        currentEditUser: {},

        //定义一信新的用户对象，用于发送到后端去添加用户
        newUser: {
          username: '',
          password: '',
          state: ''
        },

        //添加用户的对话框的开关变量
        addDialogVisible: false,

        //所有角色
        allRoles: []
      }
    },

    created() {
      this.getUsers();

      this.api.__api__getRolesAll()
        .then(data => {
          this.allRoles = data.data;
        })
    },

    methods: {


      stateChange(user) {
        if(user.username=='admin'){
          this.$message.warning("你想死呀！管理员用户不能禁用");
          user.state = Math.abs(user.state - 1);
          return;
        }
        console.log("user.state=" + user.state);

        this.api.__api__updateUser({id: user.id, state: user.state})
          .then(data => {
            if (data) {
              console.log("data=" + JSON.stringify(data));
              this.$message.success("修改用户状态成功");
              this.getUsers();
            }
          })
          .catch(error => {
            this.$message.error("修改用户状态失败");
            user.state = Math.abs(user.state - 1);
          })

      },

      searchButtonClick() {
        this.getUsers();
      },


      formatDateTime(ms) {
        return formatDateTime(ms);
      },


      addButtonClick() {
        this.addDialogVisible = true;
      },

      getUsers() {
        this.api.__api__getUsers(this.userQueryInfo)
          .then(data => {

            this.page = data.data;
          })
          .catch(error => {
          })

      },

      handleSizeChange(val) {

        this.userQueryInfo.pageSize = val;
        this.getUsers();
      },
      handleCurrentChange(val) {
        this.userQueryInfo.pageNum = val;
        this.getUsers();
      },


      deleteButtonClick(user) {
        if(user.username=='admin'){
          this.$message.warning("你想死啊! 管理员用户不能删除!");
          return;
        }
        this.$confirm("确定要删除ID为" + user.id + "用户吗?", "删除确认")
          .then(rs => {
            this.api.__api__deleteUser(user.id)
              .then(data => {
                this.$message.success("删除用户成功");
                this.getUsers();
              })
              .catch(error => {
                this.$message.error("删除用户失败");
              })
          }).catch(error => {
          console.log(error);
        })
      },

      editButtonClick(user) {
        //克隆一个对象给到变量currentEditUser,不能共用一个对象，否则还没提交修改，表格中就出现了新值
        this.currentEditUser = JSON.parse(JSON.stringify(user));
        this.editDialogVisible = true;


      },

      confirmAddUserButtonClick() {
        this.addDialogVisible = false;
        this.api.__api__addUser(this.newUser)
          .then(data => {
            this.$message.success("添加用户成功");
          })
          .catch(error => {
            this.$message.error("添加用户失败");
          })
      },

      confirmUpdateUserButtonClick() {
        this.editDialogVisible = false;
        this.api.__api__updateUser(this.currentEditUser)
          .then(data => {
            this.$message.success("修改用户成功");
            this.getUsers(); //刷数据
          })
          .catch(error => {
            this.$message.error("修改用户失败");
          })
      },

      handleRolesChange(user) {
        this.api.__api__updateRolesOfUser({userId: user.id, roleIds: user.roleIds})
          .then(data => {
            user.roleIds = data.data;
          })
      },


    }


  }
</script>

<style scoped>

</style>
